package com.phone.sdktest.window;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by Vincent
 * Email:jingwei.zhang@yeahmobi.com
 */
public final class NormalWindow implements IWindow {
    private WindowManager mWindowManager;
    private static View mView;
    private boolean isShow = false;
    private static Context context;


    private NormalWindow() {
    }


    public static final NormalWindow getInstance(Context _context, View view) {
        context = _context;
        mView = view;
        return NormalWindowHolder.INSTANCE;
    }


    private static class NormalWindowHolder {
        private static final NormalWindow INSTANCE = new NormalWindow();
    }


    public void show() {
        if (isShow) {
            return;
        }
        if (mView == null) {
            return;
        }
        int type;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //解决Android 7.1.1起不能再用Toast的问题（先解决crash）
            if (Build.VERSION.SDK_INT > 24) {
                type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        } else {
            type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        int widthAndHeight = WindowManager.LayoutParams.MATCH_PARENT;
        if (mWindowManager != null) {
            mWindowManager = null;
        }

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(widthAndHeight,
            widthAndHeight, type, WindowManager.LayoutParams.FLAG_FULLSCREEN, PixelFormat.TRANSLUCENT);
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.gravity = Gravity.CENTER;

        try {
            mWindowManager.addView(mView, wmParams);
            isShow = true;
        } catch (Exception e) {
            e.printStackTrace();
            isShow = false;
        }
    }


    public void hide() {
        if (!isShow) {return;}
        if (mWindowManager != null && mView != null) {
            // if (mView.getWindowToken())
            mWindowManager.removeView(mView);
        }
        isShow = false;
        mWindowManager = null;
        mView = null;
    }


    public void setView(View view) {
        hide();
        this.mView = view;
    }


    @Override
    public View getView() {
        return mView;
    }
}
